import { Effect, Reducer } from 'umi';

import {getUserIdentity,getviewAuthority,getApiAuthority} from '@/services/consumer';

import {IuserIdentity,IViewAuthority,IApiAuthorit} from '@/interface/consumer';

import * as consumerService from '@/services/consumer';

export interface ConsumerModelState{
    userIndentity:IuserIdentity[];
    viewAuthority:IViewAuthority[]; 
    apiAuthority:IApiAuthorit[];
}

export interface ConsumerModelType{
    namespace:'consumer',
    state:ConsumerModelState,
    effects:{
        getUserIdentity:Effect;
        getviewAuthority:Effect;
        getApiAuthority:Effect;
        submitApi:Effect;
    },
    reducers:{
        save: Reducer<ConsumerModelState>;
    }
};

const consumerModel:ConsumerModelType = {
    namespace:'consumer',
    state:{
        userIndentity:[],
        viewAuthority:[],
        apiAuthority:[]
    },
    effects:{
        //身份id
        *getUserIdentity({payload},{call,put}){
            let result = yield call(getUserIdentity);
            if(result.code === 1){
                yield put({
                    type:'save',
                    payload:{userIndentity:result.data}
                })
            }
        },
        //获取已有视图权限数据
        *getviewAuthority({payload},{call,put}){
            let result = yield call(getviewAuthority);
            if(result.code === 1){
                yield put({
                    type:'save',
                    payload:{viewAuthority:result.data}
                })
            }
        },
        //获取api权限数据
        *getApiAuthority({payload},{call,put}){
            let result = yield call(getApiAuthority);
            if(result.code === 1){
                yield put({
                    type:'save',
                    payload:{apiAuthority:result.data}
                })
            }
        },
        //提交
        *submitApi({payload},{call,put}){
            //根据payload.type 去判断你要触发那个提交函数
            const result = yield call((consumerService as {[propsName:string]:any})[payload.type],payload.data);
            return result;
        }
    },
    reducers:{
        save(state, action) {
            return {
              ...state,
              ...action.payload,
            };
        }
    }
}

export default consumerModel